package com.blockmeta.bbs.immodule.activity;

import android.content.Intent;
import android.graphics.Color;
import com.google.android.material.appbar.AppBarLayout;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import android.view.View;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.blockmeta.bbs.baselibrary.base.adapter.FragmentVPAdapter;
import com.blockmeta.bbs.baselibrary.utils.LoadPicUtil;
import com.blockmeta.bbs.baselibrary.utils.ToastUtil;
import com.blockmeta.bbs.baselibrary.widget.tab.SlidingTabLayout;
import com.blockmeta.bbs.businesslibrary.arouter.RouterPath;
import com.blockmeta.bbs.businesslibrary.base.BaseActivity;
import com.blockmeta.bbs.businesslibrary.constant.Constant;
import com.blockmeta.bbs.businesslibrary.net.pojo.BaseImResponse;
import com.blockmeta.bbs.businesslibrary.net.retrofit.RetrofitFactory;
import com.blockmeta.bbs.businesslibrary.net.rxjava.CommonSubscriber;
import com.blockmeta.bbs.businesslibrary.net.rxjava.RxUtil;
import com.blockmeta.bbs.businesslibrary.util.AccountHelper;
import com.blockmeta.bbs.businesslibrary.widget.CircleImageView;
import com.blockmeta.bbs.immodule.R;
import com.blockmeta.bbs.immodule.R2;
import com.blockmeta.bbs.immodule.activity.chat.UUChatActivity;
import com.blockmeta.bbs.immodule.bean.FansCount;
import com.blockmeta.bbs.immodule.bean.FansVO;
import com.blockmeta.bbs.immodule.bean.Params;
import com.blockmeta.bbs.immodule.bean.UserAllInfo;
import com.blockmeta.bbs.immodule.bean.UserProperty;
import com.blockmeta.bbs.immodule.corebean.Impl.IMApplicationContext;
import com.blockmeta.bbs.immodule.eventbus.UserInfoChangeEvent;
import com.blockmeta.bbs.immodule.fragment.PersionalHomePageFragment;
import com.blockmeta.bbs.immodule.net.api.AddFansApi;
import com.blockmeta.bbs.immodule.net.api.GetUserAllInfoApi;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 被产品废弃个人主页
 */
@Route(path = RouterPath.PERSONHOMEPAGE_ACTIVITY)
public class PersonalHomePageActivity extends BaseActivity {
    public static final String CONTENTTYPE_POST = "文章";
    public static final String CONTENTTYPE_FORUM = "帖子";
    public static final String CONTENTTYPE_REPLY = "评论";
    @BindView(R2.id.iv_avatar)
    CircleImageView mIvAvatar;
    @BindView(R2.id.tv_name)
    TextView mTvName;
    @BindView(R2.id.tv_signature)
    TextView mTvSignature;
    @BindView(R2.id.tv_watch_count)
    TextView mTvWatchCount;
    @BindView(R2.id.tv_fans_count)
    TextView mTvFansCount;
    @BindView(R2.id.tv_title)
    TextView mTvTitle;
    @BindView(R2.id.app_bar_layout)
    AppBarLayout mAppBarLayout;
    @BindView(R2.id.tv_watch_button)
    TextView mTvWatchButton;
    @BindView(R2.id.tv_contact_button)
    TextView mTvContactButton;
    @BindView(R2.id.tv_circle_button)
    TextView mTvCircleButton;
    @BindView(R2.id.tab_layout)
    SlidingTabLayout mTabLayout;
    @BindView(R2.id.viewpager_personalhome)
    ViewPager mViewPager;
    @BindView(R2.id.fl_next)
    View mNextView;

    @Autowired(name = Constant.ZERO)
    public String mUserId;

    private List<Fragment> fragments;
    public UserAllInfo mUserAllInfo;

    @Override
    protected boolean showTitle() {
        return false;
    }

    @Override
    public View setView() {
        return getLayoutInflater().inflate(R.layout.activity_personal_home_page, null);
    }

    @Override
    protected void initialize() {
        super.initialize();
        IMApplicationContext.getIMMetaService().register(this);

//        mUserId = "33672";
        if("0".equals(mUserId)){
            finish();
        }
        mAppBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                int titleColor = getResources().getColor(R.color.white);
                float fraction = Math.abs(verticalOffset) * 1f / appBarLayout.getTotalScrollRange();
                mTvTitle.setTextColor(changeAlpha(titleColor, fraction));
            }
        });



        mNextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mUserAllInfo==null||!checkLoginStatus()){
                    return;
                }
                UserProperty userProperty = mUserAllInfo.getUserProperty();
                if (userProperty==null){
                    return;
                }

                startActivity(new Intent(PersonalHomePageActivity.this,FriendsSettingActivity.class)
                        .putExtra(Params.USERID, Integer.parseInt(mUserId))
                        .putExtra(Params.ISSHIELD, mUserAllInfo.isShield())
                        .putExtra(Params.USER_NAME,userProperty.getUsername())
                        .putExtra(Params.USER_AVATAR,userProperty.getAvatar())
                        .putExtra(Params.USER_DESC,userProperty.getDesc()));
            }
        });
        netWork();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(mUserAllInfo != null){
            boolean isFriend = IMApplicationContext.getUserDomainService().isFriend(Integer.parseInt(mUserId));
            showBottom(mUserAllInfo.isFans(), isFriend, mUserAllInfo.isHasGroupCreate());
        }
    }

    private void netWork() {
        RetrofitFactory.getRetrofit().create(GetUserAllInfoApi.class)
                .getUserAllInfo(mUserId, AccountHelper.getUid())
                .compose(RxUtil.<BaseImResponse<UserAllInfo>>rxSchedulerHelper())
                .compose(RxUtil.<UserAllInfo>commonResult())
                .compose(this.<UserAllInfo>bindToLifecycle())
                .subscribe(new CommonSubscriber<UserAllInfo>(mContext) {
                    @Override
                    public void onNext(UserAllInfo userAllInfo) {
                        //绑定ui数据
                        mUserAllInfo = userAllInfo;
                        mTvWatchButton.setText(userAllInfo.isFans() ? R.string.im_fansed : R.string.im_unfansed);
                        mTvWatchButton.setEnabled(AccountHelper.getUidInt() != Integer.parseInt(mUserId));
                        UserProperty userProperty = mUserAllInfo.getUserProperty();
                        IMApplicationContext.getUserDomainService().updateUserAvator(mUserId, userProperty.getAvatar());

                        bindUserInfo(userProperty);
                        FansCount fansCount = mUserAllInfo.getFansCount();
                        boolean isFriend = IMApplicationContext.getUserDomainService().isFriend(Integer.parseInt(mUserId));
                        showBottom(mUserAllInfo.isFans(), isFriend, mUserAllInfo.isHasGroupCreate());
                        if(fansCount != null){
                            mTvWatchCount.setText(fansCount.getMyConcernCount() + "");
                            mTvFansCount.setText(fansCount.getMyFansCount() + "");
                        }
                        bindPostData(userProperty);
                    }
                });
    }

    private void bindPostData(UserProperty userProperty) {
        int postSize = 0;
        int userPostSize = 0;
        int userReplySize = 0;
        fragments = new ArrayList<>();
        List<String> titles = new ArrayList<>();
        if(userProperty.getIs_author() == 1){
            fragments.add(PersionalHomePageFragment.newInstance(CONTENTTYPE_POST));
            titles.add(CONTENTTYPE_POST + " " + (postSize == 0 ? "" : postSize));
        }
        fragments.add(PersionalHomePageFragment.newInstance(CONTENTTYPE_FORUM));
        titles.add(CONTENTTYPE_FORUM + " " + (userPostSize == 0 ? "" : userPostSize));
        fragments.add(PersionalHomePageFragment.newInstance(CONTENTTYPE_REPLY));
        titles.add(CONTENTTYPE_REPLY + " " + (userReplySize == 0 ? "" : userReplySize));
        FragmentVPAdapter vpAdapter = new FragmentVPAdapter(getSupportFragmentManager(), fragments);
        mViewPager.setAdapter(vpAdapter);
        mViewPager.setOffscreenPageLimit(titles.size());
        String[] pageTitles = new String[titles.size()];
        mTabLayout.setViewPager(mViewPager, titles.toArray(pageTitles));
    }

    private void bindUserInfo(UserProperty userProperty) {
        if(userProperty != null){
            mTvName.setText(userProperty.getUsername());
            String desc = userProperty.getDesc();
            String normalizeDesc = desc.length() > 30 ? desc.substring(0, 30) : desc;
            mTvSignature.setText(normalizeDesc);
            LoadPicUtil.loadWithPicasso(mIvAvatar, userProperty.getAvatar());
        }

    }

    /**
     * 根据百分比改变颜色透明度
     */
    public int changeAlpha(int color, float fraction) {
        int red = Color.red(color);
        int green = Color.green(color);
        int blue = Color.blue(color);
        int alpha = (int) (Color.alpha(color) * fraction);
        return Color.argb(alpha, red, green, blue);
    }

    @OnClick({R2.id.tv_watch_button, R2.id.tv_contact_button, R2.id.tv_circle_button,R2.id.fl_back,R2.id.v_click_region_for_fans,R2.id.v_click_region_for_watch})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.fl_back) {
            finish();

        } else if (i == R.id.tv_watch_button&&checkLoginStatus()) {
            if(AccountHelper.getUidInt() == Integer.parseInt(mUserId)){
                ToastUtil.show("不能关注自己");
                return;
            }

            RetrofitFactory.getRetrofit().create(AddFansApi.class)
                    .addFans(new FansVO(Integer.parseInt(AccountHelper.getUid()), Integer.parseInt(mUserId)))
                    .compose(RxUtil.<BaseImResponse<FansVO>>rxSchedulerHelper())
                    .compose(this.<BaseImResponse<FansVO>>bindToLifecycle())
                    .subscribe(new CommonSubscriber<BaseImResponse<FansVO>>(mContext) {
                        @Override
                        public void onNext(BaseImResponse<FansVO> fans) {
                            //绑定ui数据
                            FansVO fansVO = fans.data;
                            if (fansVO != null) {
                                mTvWatchButton.setText(R.string.im_fansed);
                                mTvWatchButton.setTextColor(Color.parseColor("#8e000000"));
                                addOrReduceFansCount(true);
                                mUserAllInfo.setFans(true);
                            } else {
                                mTvWatchButton.setText("+ 关注");
                                mTvWatchButton.setTextColor(Color.parseColor("#EE0000"));
                                addOrReduceFansCount(false);
                                mUserAllInfo.setFans(false);
                            }
                        }
                    });

        } else if (i == R.id.tv_contact_button&&checkLoginStatus()) {
            startActivity(new Intent(PersonalHomePageActivity.this, UUChatActivity.class).putExtra(Params.USER_TAG, Long.parseLong(mUserId)));

        } else if (i == R.id.tv_circle_button&&checkLoginStatus()) {
            startActivity(new Intent(PersonalHomePageActivity.this, CircleListActivity.class).putExtra(Params.USER_TAG, Integer.parseInt(mUserId)));

        } else if (i == R.id.v_click_region_for_fans) {
            //粉丝
            startActivity(new Intent(PersonalHomePageActivity.this, FansActivity.class).putExtra(Params.USER_TAG, Integer.parseInt(mUserId)));

        } else if (i == R.id.v_click_region_for_watch) {
            //关注
            startActivity(new Intent(PersonalHomePageActivity.this, WatchedActivity.class).putExtra(Params.USER_TAG, Integer.parseInt(mUserId)));
        }
    }

    private void addOrReduceFansCount(boolean add) {
        int fanCount = Integer.parseInt(mTvFansCount.getText().toString());
        if (add) {
            fanCount++;
        } else {
            fanCount--;
        }
        fanCount = fanCount > 0 ? fanCount : 0;
        mTvFansCount.setText(String.valueOf(fanCount));
    }

    private void showBottom(boolean beWatched,boolean friend,boolean circleCreated){
        mTvWatchButton.setText(beWatched?"已关注":"+ 关注");
        mTvWatchButton.setTextColor(beWatched?Color.parseColor("#8e000000"):Color.parseColor("#e60000"));

        mTvContactButton.setText(friend?"发消息":"私信");

        mTvCircleButton.setVisibility(circleCreated?View.VISIBLE:View.GONE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        IMApplicationContext.getIMMetaService().unregister(this);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(UserInfoChangeEvent msg){
        if(msg.userId == Integer.parseInt(mUserId) && msg.changeInfoMap.containsKey("shield"))
        {
            mUserAllInfo.setShield(Boolean.parseBoolean(msg.changeInfoMap.get("shield")));
        }
    }

}
